package com.mjlf.mqserver.server;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mjlf.mqserver.inter.ServerFactory;
import com.mjlf.restclient.entity.RestParams;
import com.mjlf.restclient.template.RestTemplate;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ServerServer
 * @Author mjlft
 * @Date 2020/2/19 14:46
 * @Version 1.0
 * @Description TODO
 */
@Service
public class ServerServer implements ServerFactory {

    @Value("${server.servers.path}")
    private String serverUrl;
    @Value("${server.releader.path}")
    private String releaderUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void synServer() throws Exception {
        RestParams restParams = new RestParams();
        restParams.setUrl(serverUrl);
        JSONObject jsonObject = JSONObject.parseObject(restTemplate.get(restParams));

        if(jsonObject.containsKey("data")){
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("mq-server");
            List<String> servers = new ArrayList<>();
            if(jsonArray != null){
                for(int i = 0; i < jsonArray.size(); i++){
                    JSONObject index = jsonArray.getJSONObject(i);
                    String server = index.getString("host") + ":" + index.getString("port");
                    servers.add(server);
                    if(ServerFactory.servers.contains(server)){
                        continue;
                    }else {
                        ServerFactory.servers.add(server);
                    }
                }
            }
            List<String> dedServer = new ArrayList<>();
            for(String server : ServerFactory.servers){
                if (!servers.contains(server)) {
                    String[] strings = server.split(":");
                    RestParams leaderParas = new RestParams();
                    leaderParas.setUrl(releaderUrl);
                    JSONObject p = new JSONObject();
                    p.put("host", strings[0]);
                    p.put("port", strings[1]);
                    leaderParas.setParams(p.toJSONString());

                    restTemplate.post(restParams);
                    dedServer.add(server);
                }
            }
            ServerFactory.servers.removeAll(dedServer);
        }
    }
}
